package utils

import (
	"fmt"
	"net"
	"os"
	"time"
)

type UnixSocket struct {
	SocketPath string
}

func NewUnixSocket(socketPath string) *UnixSocket {
	return &UnixSocket{
		SocketPath: socketPath,
	}
}

// Start 启动Unix Socket服务器，接收请求并处理
func (us *UnixSocket) Start(handleRequest func(r Requests, c net.Conn), done chan struct{}) error {
	// 监听Unix Socket
	os.Remove(us.SocketPath)
	ln, err := net.Listen("unix", us.SocketPath)
	fmt.Println("Listening on", us.SocketPath, time.Now().Format("2006-01-02 15:04:05"))
	if err != nil {
		fmt.Println("监听失败:", err)
		return err
	}
	defer ln.Close()

	// 启动服务器后，通知守护进程启动完成
	close(done)

	for {
		conn, err := ln.Accept()
		if err != nil {
			continue
		}
		fmt.Println("Accepted connection from", conn.RemoteAddr(), time.Now().Format("2006-01-02 15:04:05"))
		go func(c net.Conn) {
			defer c.Close()

			var req Requests
			if req, err = readRequestFromConn(c); err != nil {
				SendError(c, err.Error())
				return
			}

			fmt.Println("Received request:", req)
			handleRequest(req, c)
		}(conn)
	}
}
